const formatTime = date => {
  var date = new Date(date)
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-')
}
const formatTimeDetails = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 封封微信的的request
 */
function request(url, data = {}, method = "GET") {
  wx.showLoading({
    title: '加载中...',
  })
  return new Promise(function(resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'X-Litemall-Token': wx.getStorageSync('token')
      },
      success: function(res) {
        wx.hideLoading();
        if (res.statusCode == 200) {

          if (res.data.errno == 501) {
            // 清除登录相关内容
            try {
              wx.removeStorageSync('userInfo');
              wx.removeStorageSync('token');
            } catch (e) {
              // Do something when catch error
            }
            // 切换到登录页面
            wx.navigateTo({
              url: '/pages/login/login'
            });
          } else if (res.data.errno == 507) {
            //绑定手机
            wx.navigateTo({
              url: '/pages/bind-tel/bind-tel', //注意switchTab只能跳转到带有tab的页面，不能跳转到不带tab的页面
            })
          } else {
            resolve(res.data);
          }
        } else {
          reject(res.errMsg);
        }

      },
      fail: function(err) {
        wx.hideLoading();
        reject(err)
      }
    })
  });
};
/**
 * 封封微信的的request
 */
function gameRequest(url, data = {}, method = "GET") {
  wx.showLoading({
    title: '加载中...',
  })
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'X-Litemall-Token': wx.getStorageSync('token')
      },
      success: function (res) {
        wx.hideLoading();
        if (res.statusCode == 200) {

          if (res.data.errno == 501) {
            // 清除登录相关内容
            try {
              wx.removeStorageSync('userInfo');
              wx.removeStorageSync('token');
            } catch (e) {
              // Do something when catch error
            }
            // 切换到登录页面
            wx.navigateTo({
              url: '/pages/game/game-play/game-play'
            });
          } else if (res.data.errno == 507) {
            //绑定手机
            wx.navigateTo({
              url: '/pages/bind-tel/bind-tel', //注意switchTab只能跳转到带有tab的页面，不能跳转到不带tab的页面
            })
          } else {
            resolve(res.data);
          }
        } else {
          reject(res.errMsg);
        }

      },
      fail: function (err) {
        wx.hideLoading();
        reject(err)
      }
    })
  });
};
/**
 * 封封微信的游戏不带加载框request
 */
function gameRequestNoLoading(url, data = {}, method = "GET") {

  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'X-Litemall-Token': wx.getStorageSync('token')
      },
      success: function (res) {
       
        if (res.statusCode == 200) {

          if (res.data.errno == 501) {
            // 清除登录相关内容
            try {
              wx.removeStorageSync('userInfo');
              wx.removeStorageSync('token');
            } catch (e) {
              // Do something when catch error
            }
            // 切换到登录页面
            wx.navigateTo({
              url: '/pages/game/game-play/game-play'
            });
          } else if (res.data.errno == 507) {
            //绑定手机
            wx.navigateTo({
              url: '/pages/bind-tel/bind-tel', //注意switchTab只能跳转到带有tab的页面，不能跳转到不带tab的页面
            })
          } else {
            resolve(res.data);
          }
        } else {
          reject(res.errMsg);
        }

      },
      fail: function (err) {
      
        reject(err)
      }
    })
  });
};
/**
 * 封封微信的的noLoadingRequest不带加载框
 */
function noLoadingRequest(url, data = {}, method = "GET") {

  return new Promise(function(resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'X-Litemall-Token': wx.getStorageSync('token')
      },
      success: function(res) {

        if (res.statusCode == 200) {
          if (res.data.errno == 501) {
            // 清除登录相关内容
            try {
              wx.removeStorageSync('userInfo');
              wx.removeStorageSync('token');
            } catch (e) {
              // Do something when catch error
            }
            // 切换到登录页面
            wx.navigateTo({
              url: '/pages/login/login'
            });
          } else if (res.data.errno == 507) {
            //绑定手机
            wx.navigateTo({
              url: '/pages/bind-tel/bind-tel', //注意switchTab只能跳转到带有tab的页面，不能跳转到不带tab的页面
            })
          } else {
            resolve(res.data);
          }
        } else {
          reject(res.errMsg);
        }

      },
      fail: function(err) {

        reject(err)
      }
    })
  });
};
//ASCII排序
function objKeySort(arys) {
  //先用Object内置类的keys方法获取要排序对象的属性名数组，再利用Array的sort方法进行排序
  var newkey = Object.keys(arys).sort();
  console.log('newkey=' + newkey);
  var newObj = ''; //创建一个新的对象，用于存放排好序的键值对
  for (var i = 0; i < newkey.length; i++) {
    //遍历newkey数组
    if (arys[newkey[i]] != '') {
      newObj += [newkey[i]] + '=' + arys[newkey[i]] + '&';
    }
  }
  return newObj.substring(0, newObj.length - 1);
};

//提示框
function myToast(title) {
  wx.showToast({
    title: title,
    icon: 'none'
  })
};

//跳转界面
function toClass(path, arys) {
  wx.navigateTo({
    url: path + '?' + objKeySort(arys),
  })
};
//销毁当前界面
function toClassFinish(path, arys) {
  wx.redirectTo({
    url: path + '?' + objKeySort(arys),
  })
};
//判断是否空
function isEmpy(content) {
  if (content == '' || content == null || content == undefined || content == 'undefined') {
    return true
  } else {
    return false
  }
};
//数组转为字符串并分割
function arrToString(arr) {
  var strInput = ''
  var arr1 = arr
  if (arr1.length <= 0) {
    return ''
  } else {
    for (var i = 0; i < arr1.length; i++) {
      strInput = strInput + '_' + arr1[i]
    }
    strInput = strInput.substring(1, strInput.length);
    return strInput
  }

};
//上传文件
function uploadfile(url, filePath, name, data = {}, method = "POST") {
  wx.showLoading({
    title: '加载中',
  })
  return new Promise(function(resolve, reject) {
    wx.uploadFile({
      url: url,
      filePath: filePath,
      name: name,
      method: method,
      header: {
        "Content-Type": "multipart/form-data",
        'X-Litemall-Token': wx.getStorageSync('token')
      },
      formData: data,
      success: function(res) {
        wx.hideLoading();
        if (res.statusCode == 200) {

          if (res.data.errno == 501) {
            // 清除登录相关内容
            try {
              wx.removeStorageSync('userInfo');
              wx.removeStorageSync('token');
            } catch (e) {
              // Do something when catch error
            }
            // 切换到登录页面
            wx.navigateTo({
              url: '/pages/login/login'
            });
          } else {
            resolve(res.data);
          }
        } else {
          reject(res.errMsg);
        }
      },
      fail: function(err) {
        wx.hideLoading();
        reject(err)
      }
    })
  });
};
// 防抖节流 防止重复点击
function throttle(fn, gapTime) {
  if (gapTime == null || gapTime == undefined) {
    gapTime = 1500
  }

  let _lastTime = null

  // 返回新的函数
  return function() {
    let _nowTime = +new Date()
    if (_nowTime - _lastTime > gapTime || !_lastTime) {
      fn.apply(this, arguments) //将this和参数传给原函数
      _lastTime = _nowTime
    }
  }
}
//复制文本
function mCopy(msg) {
  wx.setClipboardData({
    data: msg,
    success: function(res) {
      // wx.showModal({
      //   title: '提示',
      //   content: '复制成功',
      //   showCancel: false
      // });
    }
  })
};
module.exports = {
  formatTime: formatTime,
  request: request,
  objKeySort: objKeySort,
  myToast: myToast,
  toClass: toClass,
  isEmpy: isEmpy,
  toClassFinish: toClassFinish,
  arrToString: arrToString,
  uploadfile: uploadfile,
  noLoadingRequest: noLoadingRequest,
  throttle: throttle,
  mCopy: mCopy,
  gameRequest: gameRequest,
  gameRequestNoLoading: gameRequestNoLoading,
  formatTimeDetails: formatTimeDetails
}